import api from '../../api';
import { isZiGuanEvir } from '../../utils/commonFunc';
import moment from 'moment';
import { message } from 'antd';

export default {
  namespace: 'productAGroupM',
  state: {
    products: undefined, // 产品列表
    productGroup: undefined, // 产品+组合列表
    productGroupList: [],
    productGroupFuZhai: undefined, //负债端的产品组合下拉
  },
  effects: {
    // 不设置rootId，获取产品+组合树形结构（数据放在state中）
    // 设置rootId，根据产品获取组合(callback形式返回)
    *getProductGroup({ payload, callback }, { call, put, select }) {
      let { rootId, authority, maatApi, investmentType, inveType, tradeModel } = payload;
      let args = rootId ? { rootId: rootId } : {};
      if (tradeModel) args.tradeModel = payload.tradeModel.join(',');
      if (inveType != undefined) args.inveType = inveType;
      let res;
      if (payload.productCode) {
        args.productCode = payload.productCode; //通过productCode来查询树形 负债端维护
        res = yield call(api.getProductGroup, args);
        if (res && res.success) {
          // 处理树形结构，value title children disabled
          let readNodes = (nodes = []) => {
            for (let item of nodes) {
              item.value = !payload.productCode ? item.key : item.portfolioCode;
              item.title = `${item.portfolioCode} - ${item.portfolioName}`;
              item.disabled = authority === 'read' ? (item.queryPermission === true ? false : true) : item.operationPermission === true ? false : true;

              if (item.children && item.children.length) readNodes(item.children);
            }
          };

          readNodes(res.data);
          yield put({
            type: 'setState',
            payload: {
              productGroupFuZhai: res.data,
            },
          });
          callback(res.data);
          return;
        }
      }
      if (investmentType === 'FB') {
        // 获取产品-组合树形结构
        args.investmentType = investmentType;
        res = yield call(api.queryProductsAndPortfolios, args);
        if (res && res.success) {
          // 处理树形结构，value title children disabled
          let compNodes = (nodes = []) => {
            nodes.forEach((node) => {
              node.value = node.key || node.id;
              node.title = `${node.portfolioCode} - ${node.portfolioName}`;
              if (node.id) {
                node.key = node.id;
              } else {
                node.disabled = authority === 'read' ? (node.queryPermission === true ? false : true) : node.operationPermission === true ? false : true;
              }
              if (node.children && Array.isArray(node.children)) {
                compNodes(node.children);
              }
            });
          };
          compNodes(res.data);
          yield put({
            type: 'setState',
            payload: {
              productGroupList: res.data,
            },
          });
          callback(res.data);
          return;
        }
      } else {
        res = yield call(api.getProductGroup, args);
      }

      if (res && res.success) {
        // 处理树形结构，value title children disabled
        let readNodes = (nodes = []) => {
          for (let item of nodes) {
            item.value = !payload.productCode ? item.key : item.portfolioCode;
            item.title = `${item.portfolioCode} - ${item.portfolioName}`;
            item.disabled = authority === 'read' ? (item.queryPermission === true ? false : true) : item.operationPermission === true ? false : true;

            if (item.children && item.children.length) readNodes(item.children);
          }
        };
        readNodes(res.data);
        if (payload && payload.rootId) {
          callback(res.data);
        } else {
          yield put({
            type: 'setState',
            payload: {
              productGroup: res.data,
            },
          });
          // callback();
          callback(res.data);
        }
      }
    },

    // 获取产品列表
    *getProducts({ payload, callback }, { call, put, select }) {
      if (!payload.exist) {
        delete payload.exist;
      }
      if (payload.verificationModeGZ == undefined) {
        delete payload.verificationModeGZ;
      }
      if (!payload.tradeModel) {
        delete payload.tradeModel;
      } else {
        payload.tradeModel = payload.tradeModel.join(',');
      }
      // 组合根节点
      if (payload.dataType == 1) {
        delete payload.dataType;

        let withMAAT = false;
        let temp;
        if (payload.maatApi) {
          // 判断当前环境是不是资管
          temp = isZiGuanEvir();
          if (!!temp && temp['iv-user']) withMAAT = true;
        }
        delete payload.maatApi;
        let res;
        if (withMAAT) {
          payload.createdBy = temp['iv-user'];
          res = yield call(api.getProductsWithMAAT, payload);
        } else {
          res = yield call(api.getProducts, payload);
        }
        if (res && res.success) {
          res.data.forEach((item) => {
            item.value = item.id;
            item.title = `${item.portfolioCode} - ${item.portfolioName}`;
          });

          yield put({
            type: 'setState',
            payload: {
              products: res.data,
            },
          });
          callback(res.data);
        }
      }
      // 真实的产品节点
      if (payload.dataType == 2 || payload.dataType == 3) {
        let res;
        let dataType = payload.dataType;
        delete payload.dataType;
        delete payload.maatApi;
        dataType == 2 ? (res = yield call(api.getProducts1, payload)) : (res = yield call(api.getProducts2, payload));

        if (res && res.success) {
          res.data.forEach((item) => {
            item.code = item.value;
            item.mame = item.title;
            item.title = `${item.code} - ${item.title}`;
            item.value = item.id;
          });

          yield put({
            type: 'setState',
            payload: {
              products: res.data,
            },
          });
          callback(res.data);
        } else {
          message.error('获取产品失败。');
        }
      }

      // 投资经理权限产品
      if (payload.dataType == 4 || payload.dataType == 5) {
        let dataType = payload.dataType;
        delete payload.dataType;
        let withMAAT = false;
        let temp;
        if (payload.maatApi) {
          // 判断当前环境是不是资管
          temp = isZiGuanEvir();
          if (!!temp && temp['iv-user']) withMAAT = true;
        }
        delete payload.maatApi;
        let res;
        if (withMAAT) {
          payload.createdBy = temp['iv-user'];
          res = yield call(api.getProducts3, payload);
        } else {
          res = yield call(api.getProducts3, payload);
        }

        if (res && res.code == 0) {
          if (dataType == 4) {
            let dataSource = res.data.dataSource.filter((item) => item.isSimulate != 1);
            res.data.dataSource = dataSource;
          }
          res.data.dataSource.forEach((item) => {
            item.code = item.productCode;
            item.mame = item.productName;
            item.title = `${item.isSimulate == 1 ? '[模拟]' : ''}${item.productCode} - ${item.productName}`;
            item.value = item.productId;
          });

          yield put({
            type: 'setState',
            payload: {
              products: res.data.dataSource,
            },
          });
          callback(res.data.dataSource);
        }
      }
    },

    // 获取产品组列表
    *getProductGroups({ payload, callback }, { call, put, select }) {
      if (!payload.tradeModel) {
        delete payload.tradeModel;
      } else {
        payload.tradeModel = payload.tradeModel.join(',');
      }
      // 该接口在产品组页面用于获取产品组表格，一般情况下，需要传页码，但在下拉场景下，要全部获取
      const res = yield call(api.getProductDataList, payload);
      if (res && res.code == '0') {
        callback({
          // 将列表数据和全量数据返回
          groupsList: res.data,
          groupsFullData: res.data,
        });
      } else {
        callback({
          // 数据未正常返回，则清空
          groupsList: [],
          groupsFullData: [],
        });
      }
    },
    // 根究id查询产品信息
    *getProductById({ payload, callback }, { call, put, select }) {
      const response = yield call(api.productMange.detailInfo, payload);
      if (response && response.code == 0) {
        response?.data?.dataSource?.forEach((item) => {
          // 为保持和组合根节点相同的对象名，添加的字段
          item.portfolioCode = item.baseInfo?.code;
          item.portfolioName = item.baseInfo?.name;
          item.inveType = item.baseInfo?.inveType;
          item.status = item.baseInfo?.status;
          item.selectStartDate = item.baseInfo?.startDate;
          item.selectEndDate = item.baseInfo?.endDate || moment().subtract(1, 'days').format('YYYY-MM-DD'); //当不存在结束日期时，默认取前一天
        });
        callback(response.data.dataSource);
      } else {
        callback('fail');
      }
    },
  },

  reducers: {
    setState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
